import React, { useState, useEffect } from 'react';
import { NavLink, useNavigate } from 'react-router-dom';
import { Input, Button, Table, Radio, Switch, message, Modal, Select } from 'antd'
import { ExclamationCircleFilled } from '@ant-design/icons'
import ExportJsonExcel from "js-export-excel"
import { getDoctorList, getOfOrg, getOfTeam, getDoctorRole, deleteDoctor, updateDoctorStates, searchDoctor, filterMechanismById, getOrglist, getMngtable } from '../../../../api/Datas'
import './DataDoctor.scss'
interface Props {

}
const { Search } = Input;
const { confirm } = Modal;
function DataDoctor(props: Props) {
    const [selectionType, setSelectionType] = useState<'checkbox' | 'radio'>('checkbox');
    var [truelist, setTruelist] = useState([])
    var [list, setList] = useState([])
    var [oldList, setOldList] = useState([])
    var [option, setOption] = useState([])
    var [ofteam, setOfteam] = useState([])
    var [role, setRole] = useState([])
    var [key, setKey] = useState('')
    var navigate = useNavigate()
    var [oforg, setOforg] = useState('')
    var [team, setTeam] = useState('')
    var [tags, setTags] = useState('')
    var [loading, setLoading] = useState(false)
    var [pagination, setPagination] = useState({ current: 1, pageSize: 10, total: 100 })
    // 挂载阶段
    useEffect(() => {
        getList()
        getManagerList()
        getteamlist()
        doctorRole()
        setPagination({
            ...pagination, total: list.length
        })
    }, [])
    // 获取医生列表
    var getList = async () => {
        var res = await getDoctorList()
        if (res.data.code == 200) {
            setList(res.data.data)
            setOldList(res.data.data)
            setLoading(false)
        }

    }
    // 获取所属机构下拉框
    var getManagerList = async () => {
        var res = await getOrglist()
        var arr = res.data.data.map((item: any) => {
            return { value: item.mechanismId, label: item.mechanismName }
        })
        setOption(arr)
    }
    // 获取所属团队列表
    var getteamlist = async () => {
        var res = await getMngtable()
        console.log(res)
        var arr = res.data.data[0].map((item: any) => {
            return { value: item.teamId, label: item.teamName }
        })
        setOfteam(arr)
    }
    // 获取医生角色
    var doctorRole = async () => {
        var res = await getDoctorRole()
        var arr = res.data.map((item: any) => {
            return { value: item.id, label: item.name }
        })
        setRole(arr)
    }
    // 多选
    const rowSelection = {
        onChange: (selectedRowKeys: any, selectedRows: any) => {
            console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
            setTruelist(selectedRowKeys)
        }
    }
    // 分页发生改变后执行
    const handleChange = (pagi: any) => {
        setPagination(pagi) //更新页码
        setLoading(true)
        // 请求新的页码对应的数据
        getDoctorList().then(res => {
            if (res.status == 200) {
                setLoading(false)
                setPagination({
                    ...pagi, total: res.data.length
                })
            }
        })
    }
    // 改变状态
    const onChange = async (checked: any, id: any) => {
        var res = await updateDoctorStates({ id: id })
        console.log(res)
        if (res.data.code == 200) {
            if (checked) {
                message.success({ content: '已启用' })
            } else {
                message.success({ content: '已禁用' })
            }
        }

    }
    // 点击删除
    const showConfirm = (id: any) => {
        confirm({
            title: '删除确认',
            icon: <ExclamationCircleFilled />,
            content: '医生信息删除后无法恢复，确定删除吗？',
            okText: "确认",
            cancelText: "取消",
            onOk() {
                deleteDoctor({ id }).then((res: any) => {
                    console.log(res)
                    if (res.data.code == 200) {
                        message.success({ content: '删除成功' })
                        getList()
                    }
                })
            },
            onCancel() {
                console.log('已取消');
            },
        });
    }
    // 表格
    const columns = [
        {
            title: '编号', //表格头的标题
            dataIndex: 'doctorId', //数据索引，决定通过哪个属性名（字段名）获取数据
            key: 'doctorId',
        },
        {
            title: '头像',
            dataIndex: 'doctorImg',
            key: 'doctorImg',
            render: (_: any, record: any) => {
                return (
                    <img src={record.doctorImg} />
                )
            }
        },
        {
            title: '姓名',
            dataIndex: 'doctorName',
            key: 'doctorName',
        },
        {
            title: '联系电话',
            dataIndex: 'doctorTel',
            key: 'doctorTel',
        },
        {
            title: '角色',
            dataIndex: 'roleId',
            key: 'roleId',
            render: (_: any, record: any) => {
                return (
                    <p>
                        {role.map((item: any) => item.value == record.roleId && item.label)}
                    </p>
                )
            }
        },
        {
            title: '所属机构',
            dataIndex: 'mechanismId',
            key: 'mechanismId',
            render: (_: any, record: any) => {
                return (
                    <p>
                        {option.map((item: any) => item.value == record.mechanismId && item.label)}
                    </p>
                )
            }

        },
        {
            title: '所属团队',
            dataIndex: 'teamId',
            key: 'teamId',
            render: (_: any, record: any) => {
                return (
                    <p>
                        {ofteam.map((item: any) => item.value == record.teamId && item.label)}
                    </p>
                )
            }
        },
        {
            title: '状态',
            dataIndex: 'doctorState',
            key: 'doctorState',
            render: (_: any, record: any) => {
                return (
                    <Switch checkedChildren="启用" unCheckedChildren="禁用" defaultChecked={record.doctorState}
                        onChange={(checked, id) => { onChange(checked, record.doctorId) }}
                    />
                )
            }
        },
        {
            title: '操作',
            dataIndex: 'handle',
            key: 'handle',
            render: (_: any, record: any) => { //动态渲染当前列的数据，和dataIndex有冲突
                return (
                    <>
                        <NavLink className='handle' to='/index/datas-doctor-detail' state={record}>查看详情</NavLink>
                        <NavLink className='pen' to='/index/datas-doctor-adddoctor' state={{ record, type: 'handle' }}>编辑</NavLink>
                        <a className='delete'
                            onClick={(id) => { showConfirm(record.doctorId) }}
                        >删除</a>
                    </>
                )
            }
        },
    ]
    // 导出
    let excel = () => {//导出Excel表
        let sheetFilter = ["doctorId", "doctorImg", 'doctorName', 'doctorTel', 'roleId', "mechanismId", "teamId","doctorState"]//需要导出的属性，一般列表数据的属性
        let option = { fileName: "", datas: [{}] };
        option.fileName = "待处理服务列表";
        option.datas = [
            {
                sheetData: list,//需要导出的数据
                sheetName: "待处理服务列表",
                sheetFilter: sheetFilter,
                sheetHeader: ["团队编号", "头像", "姓名", "联系电话", "角色", "所属机构", "所属团队","状态"],//每一列的列头
                columnWidth: [20, 20, 20, 20],//每一列的宽
            }
        ]
        let toExcel = new ExportJsonExcel(option);
        toExcel.saveExcel();
    }
    // 所属机构内容发生变化
    var oforgChange =  (value: any) => {
        setOforg(value)
        if(value){
            var arr = oldList.filter((item:any)=>item.mechanismId==value)
            setList(arr)
            if(arr.length){
                message.success({content:'查询成功'})
            }else{
                message.warning({content:'暂无数据'})
            }
        }else{
            getList()
        }
    }
    // 所属团队内容发生变化
    var teamChange =  (value: any) => {
        setTeam(value)
        if(value){
            var arr = oldList.filter((item:any)=>item.mechanismId==oforg&&item.teamId==value)
            setList(arr)
            if(arr.length){
                message.success({content:'查询成功'})
            }else{
                message.warning({content:'暂无数据'})
            }
        }else{
            getList()
        }
    }


    // 医生标签内容发生变化
    var tagChange = async (value: any) => {
        setTags(value)
        var res = await getDoctorList({ oforg_like: oforg, team_like: team, role_like: value })
        setList(res.data)
        if (res.data.length) {
            message.success({ content: '查询成功' })
        } else {
            message.warning({ content: '暂时没有此条数据' })
        }
    }
    // 点击搜索的时候
    const onSearch = async (value: string) => {
        var res = await searchDoctor({ name: value })
        if (res.data.code == 200) {
            setList(res.data.data)
            if (value !== '' && res.data.data.length) {
                message.success({ content: '查询成功' })
            } else if (value !== '' && !res.data.data.length) {
                message.warning({ content: '暂时没有此条数据' })
            }
        }
    }
    return (
        <div className='data-doctor'>
            <div className="title">
                <div className='leftborder'></div>
                <h3>医生管理</h3>
            </div>
            {/* 顶部第一层 */}
            <div className="top">
                {/* 下拉框选择器 */}
                <div className="sleft">
                    <div className="leftone">
                        <span className='about'>所属机构</span>
                        <Select
                            allowClear
                            placeholder='请选择所属机构'
                            style={{ width: 200 }}
                            onChange={(value) => { oforgChange(value) }}
                            options={option}
                        />
                    </div>
                    <div className="leftone">
                        <span className='about'>所属团队</span>
                        <Select
                            allowClear
                            placeholder='请选择所属团队'
                            style={{ width: 200 }}
                            onChange={(value) => { teamChange(value) }}
                            options={ofteam}
                        />
                    </div>

                </div>
                {/* 新增/导出 */}
                <div className="sright">
                    <NavLink to='/index/datas-doctor-adddoctor' state={{ type: 'add' }}> <Button type="primary">新增医生信息</Button></NavLink>
                    <Button onClick={excel}>导出</Button>
                </div>

            </div>
            <Search placeholder="请输入医生姓名关键字"
                onSearch={onSearch}
                style={{ width: 300 }}
                allowClear
            />

            <Radio.Group
                onChange={({ target: { value } }) => {
                    setSelectionType(value);
                }}
                value={selectionType}
            >
            </Radio.Group>
            {/* <Table columns={columns} dataSource={list} pagination={pagination} onChange={(pagi)=>{handleChange(pagi)}} loading={loading}/> */}
            <Table
                rowSelection={{
                    type: selectionType,
                    ...rowSelection,
                }}
                pagination={pagination}
                onChange={(pagi) => { handleChange(pagi) }}
                loading={loading}
                dataSource={list}
                columns={columns} />
        </div>
    );
}

export default DataDoctor;